package com.project.common.resolvers;

import com.project.common.headers.Headers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @Description: i18n国际化
 * @Author: zhuchi
 * @CreateDate: 2020/8/1 18:40
 * @Version: 1.0
 */
@Slf4j
public class LanguageLocaleResolverConfig implements LocaleResolver {

    /**
     * i18n国际化
     * @param httpServletRequest
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //从Header中获取前端语言
        String language_type = httpServletRequest.getHeader(Headers.LANGUAGE_TYPE);

        //设置默认语言
        Locale locale = httpServletRequest.getLocale();
        if (!StringUtils.isEmpty(language_type)) {
            //验证前端传递过来的语言后端是否支持
            boolean haveLanguage = false;
            for (String language : Headers.LANGUAGES){
                if (language.equals(language_type)){
                    haveLanguage = true;
                }
            }
            if (haveLanguage){
                String[] split = language_type.split("_");
                locale = new Locale(split[0], split[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
